package com.lvy.hczn.transmit.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lvy.hczn.front.common.constant.MqConstants;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.system.domain.business.TransferOrder;
import com.lvy.hczn.front.system.domain.business.Warehouse;
import com.lvy.hczn.front.system.service.WarehouseService;
import com.lvy.hczn.mq.rocket.ParamInfo;
import com.lvy.hczn.mq.rocket.ProducerUtil;
import com.lvy.hczn.transmit.domain.dto.cteck.TransferTask;
import com.lvy.hczn.transmit.service.TTransferService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TTransferServiceImpl implements TTransferService {

    @Autowired
    private ProducerUtil producerUtil;

    @Autowired
    private WarehouseService warehouseService;

    /**
     * 调拨单同步，调拨任务推送，接口设计过于复杂，调拨分拣接口只需要告知哪个仓库要分拣什么商品，怎么分拣即可，什么总仓调前置仓，前置仓调总仓，应调拨运输接口告知，重构数据结构必须改
     *
     * @param request
     * @param info
     * @return
     * @author yw
     * @date 2023-06-07 13:46:43
     */
    @Override
    public void syncTransferFromPlatform(HttpServletRequest request, ParamInfo info) {
        if (info.getList() != null && !info.getList().isEmpty()) {
            log.error("syncTransferFromPlatform:{}", JSON.toJSONString(info));
            List<TransferTask> listTransferTask = JSON.parseArray(JSON.toJSONString(info.getList()), TransferTask.class);

            LinkedHashMap<String, List<TransferTask>> associationMap = listTransferTask.stream().collect(Collectors.groupingBy(TransferTask::getAssociationRepId, LinkedHashMap::new, Collectors.toList()));
            // 同步数据
            associationMap.forEach((key, value) -> {
                // 合并总仓下调拨单
                List<TransferOrder> transferOrderList = new ArrayList<>();
                value.forEach(transferTask -> {
                    transferOrderList.addAll(transferTask.getOrderInfos());
                });
                // 根据调拨仓库分组。
                Map<String,List<TransferOrder>> transferOrderMap = transferOrderList.stream().collect(Collectors.groupingBy(TransferOrder::getStartReqId));
                transferOrderMap.forEach((startReqId,list) ->{
                    //根据topic+仓库及后缀组成TAG发送到仓库
                    Warehouse warehouse = warehouseService.getOne(Wrappers.<Warehouse>lambdaQuery().eq(Warehouse::getWarehouseCode, startReqId).last("limit 1"));

                    if (warehouse != null) {
                        String topic = warehouseService.selectRegionAreaTopic(warehouse);
                        String tag = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_TRANSFER;
                        ParamInfo<TransferOrder> paramInfo = new ParamInfo<>();
                        paramInfo.setList(list);
                        try {
                            producerUtil.sendAsyncMsg(topic, tag, JSON.toJSONString(paramInfo).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
                        } catch (Exception e) {
                            throw new UtilException("数据发送异常");
                        }
                    } else {
                        throw new UtilException("目的/调入仓编码" + key + "未查询到仓库信息");
                    }
                });
            });
        } else {
            log.error("syncTransferFromPlatformError:{}", JSON.toJSONString(info));
            throw new UtilException("数据为空");
        }
    }
}
